package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.entity.Room;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.RoomMapper;
import com.zzyl.mapper.RoomTypeMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class BedServiceImpl implements BedService {


    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RoomTypeMapper roomTypeMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    @Override
    public void addRoomType(BedDto bedDto) {
        //判断床位编号不能重复
        Bed bedDB = bedMapper.getBedByBedNumber(bedDto.getBedNumber());
        if(bedDB!=null){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
        }

        Bed bed = new Bed();
        BeanUtil.copyProperties(bedDto, bed);
        bed.setBedStatus( 0 );//默认未入住
        bedMapper.addBed(bed);
        //修改房型对应的床位数
        //1、根据roomId查询床位对应的房间信息
        Room room = roomMapper.selectById(bedDto.getRoomId());
        if(room!=null){
            //根据房型名称，修改对应房型的床位数
            roomTypeMapper.incrBedCountByRoomTypeName(room.getTypeName());
        }
    }


    @Override
    public BedVo findBedById(Long id) {
        Bed bed = bedMapper.getBedById(id);
/*        BedVo bedVo = new BedVo();
        BeanUtil.copyProperties(bed, bedVo);*/
        return BeanUtil.copyProperties(bed, BedVo.class);
    }

    @Override
    public void modifyBed(BedDto bedDto) {
        //select count(1) from bed where bed_number = #{bedNumber}  and id != #{id}
        //判断状态必须是0才可以修改，此处需从数据库查询，前端不返回数据
        Integer bedStatus = bedMapper.getBedById(bedDto.getId()).getBedStatus();
        if(bedStatus!=0){
            throw new BaseException(BasicEnum.BED_EDIT_FAIL_INUSE);
        }
        //判断床位编号不能重复
        Long count = bedMapper.countDiffBedNumber(bedDto.getBedNumber(),bedDto.getId());
        if(count>0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
        }

        Bed bed = BeanUtil.copyProperties(bedDto, Bed.class);
        bedMapper.modifyBed(bed);
    }

    @Override
    public void deleteBed(Long id) {
        //根据床位id查询对应的床位
        Bed bed = bedMapper.getBedById(id);
        if(bed != null){
            bedMapper.deleteBedById(id);

            //修改对应房型的床位数
            Room room = roomMapper.selectById(bed.getRoomId());
            if(room!=null){
                roomTypeMapper.decrBedCountByRoomTypeName(room.getTypeName());
            }
        }

    }

}

